#include "medicalrecordviewwidget.h"
#include "ui_medicalrecordviewwidget.h"
#include "../../network/networkclient.h"
#include "medicalrecorddetailwidget.h"
#include "chatwindow.h"
#include <QJsonArray>
#include <QPushButton>
#include <QHBoxLayout>

MedicalRecordViewWidget::MedicalRecordViewWidget(const Patient& patient, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MedicalRecordViewWidget),
    m_patient(patient) {
    ui->setupUi(this);
    
    ui->recordTable->setColumnCount(6);
    ui->recordTable->setHorizontalHeaderLabels(
        {"病历ID", "就诊时间", "医生", "诊断", "操作", "联系医生"});
    ui->recordTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->recordTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    
    // 设置列宽模式
    ui->recordTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui->recordTable->setColumnWidth(0, 80);
    ui->recordTable->verticalHeader()->setDefaultSectionSize(40);
    ui->recordTable->setColumnWidth(1, 150);
    ui->recordTable->setColumnWidth(2, 120);
    ui->recordTable->setColumnWidth(4, 100); // 操作列
    ui->recordTable->setColumnWidth(5, 100); // 联系医生列
    ui->recordTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    ui->recordTable->setColumnWidth(4, 120); // 操作列加宽
    
    // 隐藏行号列避免乱码
    ui->recordTable->verticalHeader()->setVisible(false);
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &MedicalRecordViewWidget::onMessageReceived);
    
    loadMedicalRecords();
}

MedicalRecordViewWidget::~MedicalRecordViewWidget() {
    delete ui;
}

void MedicalRecordViewWidget::on_refreshButton_clicked() {
    loadMedicalRecords();
}

void MedicalRecordViewWidget::onViewDetailClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int row = btn->property("row").toInt();
    
    if (row >= 0 && row < m_records.size()) {
        // 将JSON转换为MedicalRecord对象
        QJsonObject recordObj = m_records[row].toObject();
        MedicalRecord record = MedicalRecord::fromJson(recordObj);
        
        // 直接创建详情widget作为独立窗口
        MedicalRecordDetailWidget *detailWidget = new MedicalRecordDetailWidget(record, nullptr);
        detailWidget->setWindowModality(Qt::ApplicationModal);
        detailWidget->show();
    }
}

void MedicalRecordViewWidget::onChatWithDoctorClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (!btn) return;
    
    int doctorId = btn->property("doctorId").toInt();
    QString doctorName = btn->property("doctorName").toString();
    
    // 打开聊天窗口
    ChatWindow* chatWindow = new ChatWindow(m_patient.id, doctorId, doctorName, "医生", this);
    chatWindow->setWindowModality(Qt::ApplicationModal);
    chatWindow->show();
}

void MedicalRecordViewWidget::loadMedicalRecords() {
    QJsonObject request;
    request["patientId"] = m_patient.id;
    NetworkClient::instance().sendRequest(MSG_GET_MEDICAL_RECORDS, request);
}

void MedicalRecordViewWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_MEDICAL_RECORDS_RESPONSE) {
        if (data["success"].toBool()) {
            m_records = data["records"].toArray();
            updateRecordTable(m_records);
        }
    }
}

void MedicalRecordViewWidget::updateRecordTable(const QJsonArray& records) {
    ui->recordTable->setRowCount(0);
    
    for (const QJsonValue& value : records) {
        QJsonObject record = value.toObject();
        
        int row = ui->recordTable->rowCount();
        ui->recordTable->insertRow(row);
        
        ui->recordTable->setItem(row, 0, 
            new QTableWidgetItem(QString::number(record["id"].toInt())));
        ui->recordTable->setItem(row, 1, 
            new QTableWidgetItem(record["visit_time"].toString()));
        ui->recordTable->setItem(row, 2, 
            new QTableWidgetItem(record["doctor_name"].toString()));
        ui->recordTable->setItem(row, 3, 
            new QTableWidgetItem(record["diagnosis"].toString()));
        
        // 第4列：操作（查看详情）
        QPushButton* viewBtn = new QPushButton("查看详情");
        viewBtn->setMinimumHeight(30);
        viewBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        viewBtn->setProperty("row", row);
        connect(viewBtn, &QPushButton::clicked, this, &MedicalRecordViewWidget::onViewDetailClicked);
        ui->recordTable->setCellWidget(row, 4, viewBtn);
        
        // 第5列：联系医生（独立列）
        int doctorId = record["doctor_id"].toInt();
        QString doctorName = record["doctor_name"].toString();
        
        QPushButton* chatBtn = new QPushButton("联系医生");
        chatBtn->setMinimumHeight(30);
        chatBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        chatBtn->setProperty("doctorId", doctorId);
        chatBtn->setProperty("doctorName", doctorName);
        chatBtn->setStyleSheet(
            "QPushButton { background-color: #07C160; color: white; border-radius: 3px; }"
            "QPushButton:hover { background-color: #06AD56; }");
        connect(chatBtn, &QPushButton::clicked, this, &MedicalRecordViewWidget::onChatWithDoctorClicked);
        ui->recordTable->setCellWidget(row, 5, chatBtn);
    }
}


